/*
 * Copyright (C) 2011  John Lawrence thegordo.john at gmail.com
 * Licensed under GPLv3 or later. see http://www.gnu.org/copyleft/gpl.html
 */

package org.jklawrencefam.server.smtp.command;

import org.jklawrencefam.annotation.smtp.SmtpCommandMarker;
import org.jklawrencefam.annotation.smtp.SmtpCommandProcessor;
import org.jklawrencefam.server.smtp.SmtpCode;
import org.jklawrencefam.server.smtp.state.StateParameters;

import java.io.InputStream;
import java.util.Scanner;

/**
 * User: John Lawrence
 * Date: 7/25/11
 * Time: 4:16 PM
 */
@SmtpCommandMarker(EnhancedHello.NAME)
public class EnhancedHello extends SmtpCommand {
    public static final String NAME = "EHLO";

    private String domain;

    protected EnhancedHello(String CommandString) {
        super(CommandString);
    }

    @Override
    public String getReplyMessage() {
        String SmtpBeginReply = SmtpCode.OK + " " + smtpProtocol.getHostname() + " ";
        StringBuilder builder = new StringBuilder(SmtpBeginReply).append(domain);
        InputStream resourceAsStream = getClass().getResourceAsStream(SmtpCommandProcessor.ENHANCED_FILENAME);
        if (resourceAsStream != null) {
            Scanner scanner = new Scanner(resourceAsStream);
            while (scanner.hasNextLine()) {
                String key = scanner.nextLine();
                builder.append(SmtpBeginReply).append(key).append("\n");
            }
        }

        return builder.toString();
    }

    @Override
    protected boolean isValid() {
        return domain != null;
    }

    @Override
    protected void processArgumentString() {
        if (argumentString != null) {
            domain = argumentString.split(" ")[0];
        }
    }

    @Override
    protected void doProcessInternal() {
        state.setParameter(StateParameters.ClientDomain, domain);
    }
}
